package com.ruoyi.coupons.listener;
import com.rabbitmq.client.Channel;
import com.ruoyi.coupons.domain.MemberCoupon;
import com.ruoyi.coupons.service.CouponService;
import com.ruoyi.coupons.service.MemberCouponService;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;

@Component
public class RabbitMqListener {
    @Autowired
    CouponService couponService;
    @Autowired
    MemberCouponService memberCouponService;
    @Autowired
    @Qualifier("couponRedisTemplate")
    private RedisTemplate<String, Object> redisTemplate;

    @RabbitListener(queues = "couponQ")
    @Transactional
    public void handleCoupon(MemberCoupon memberCoupon, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
        String stockKey = "coupon:stock:" + memberCoupon.getCouponId();
        String userLimitKey = "coupon:user:" + memberCoupon.getMemberId() + ":" + memberCoupon.getCouponId();
        try {
            int limit = couponService.getLimit(memberCoupon.getCouponId());

            // 检查唯一约束（幂等性）
            MemberCoupon existingRecord = memberCouponService.getMemberCoupon(memberCoupon);
            System.out.println(existingRecord);

            if (existingRecord != null) {
                System.out.println(existingRecord.getMcId());
                if (existingRecord.getNumber() + 1 > limit) {
                    throw new RuntimeException("超出限领数量");
                }
                System.out.println(limit);
                memberCouponService.updateNum(existingRecord.getMcId(),limit);
                System.out.println("数量更新成功");
            } else {
                memberCouponService.save(memberCoupon);
                System.out.println("添加成功");
            }

            // 减库存
            int rows = couponService.decreaseStock(memberCoupon.getCouponId());
            if (rows == 0) {
                throw new RuntimeException("数据库库存不足");
            }

            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            try {
                // 回滚 Redis
                redisTemplate.opsForValue().increment(stockKey,memberCoupon.getNumber());
                redisTemplate.opsForValue().decrement(userLimitKey,memberCoupon.getNumber());
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

}
